// 测试链接：https://www.luogu.com.cn/problem/P1902
// 请同学们务必参考如下代码中关于输入、输出的处理
// 这是输入输出处理效率较高的写法
// 提交以下的所有代码，可以直接通过

#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1010;
int n, m, p[MAXN][MAXN];
int move[5] = {-1, 0, 1, 0, -1};
bool visited[MAXN][MAXN];

inline int read()
{
    char ch = getchar();
    int x = 0, f = 1;
    while(ch < '0' || ch > '9')
    {
        if(ch == '-') f = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        x = 10 * x + ch - '0';
        ch = getchar();
    }
    return f * x;
}

bool dfs(int x, int y, int P)
{
    if(x == n) return true;
    visited[x][y] = true;
    for(int i = 0; i < 4; ++i)
    {
        int nx = x + ::move[i], ny = y + ::move[i + 1];
        if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && !visited[nx][ny] && p[nx][ny] <= P)
        {
            // P越大，越容易返回true
            if(dfs(nx, ny, P)) return true;
        }
    }
    return false;
}

bool bfs(int pos, int P)
{
    int q[(n + 1) * m];
    bool vis[(n + 1) * m];
    memset(q, 0, sizeof q);
    memset(vis, 0, sizeof vis);
    int l = 0, r = 0;
    q[r++] = pos;
    vis[pos] = true;
    while(l < r)
    {
        pos = q[l++];
        if(pos / (n + 1) == n) return true;
        for(int i = 0; i < 4; ++i)
        {
            int nx = pos / (n + 1) + ::move[i];
            int ny = pos % (n + 1) + ::move[i + 1];
            if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && !vis[nx * (n + 1) + ny] && p[nx][ny] <= P)
            {
                q[r++] = nx * (n + 1) + ny;
                vis[nx * (n + 1) + ny] = true;
            }
        }
    }
    return false;
}

int compute1()
{
    int l = 0, r = 1001, mid, ans = 0;
    while(l <= r)
    {
        mid = l + ((r - l) >> 1);
        memset(visited, 0, sizeof visited);
        if(dfs(1, 1, mid))
        {
            ans = mid;
            r = mid - 1;
        }
        else l = mid + 1;
    }
    return ans;
}

int compute2()
{
    int l = 0, r = 1001, mid, ans = 0;
    while(l <= r)
    {
        mid = l + ((r - l) >> 1);
        if(bfs(n + 2, mid))
        {
            ans = mid;
            r = mid - 1;
        }
        else l = mid + 1;
    }
    return ans;
}

int main()
{
    n = read(), m = read();
    for(int i = 1; i <= n; ++i)
    {
        for(int j = 1; j <= m; ++j)
        {
            p[i][j] = read();
        }
    }
    printf("%d\n", compute1());
    // printf("%d\n", compute2());

    return 0;
}